#include "connection.h"
#include <QDebug>
#include <QSqlQuery>

static QSqlDatabase db;

Connection::Connection()
{
}

Connection::~Connection()
{
    if (db.isOpen())
    {
        db.close();
    }
}

QSqlDatabase& Connection::getDatabase()
{
    return db;
}

QString Connection::getDatabaseName()
{
    QString db("affairs.db");

#ifdef ANDROID
    db = "/sdcard/affairs/affairs.db";
#endif

    return db;
}

bool Connection::createConnection()
{
    if (!db.isOpen())
    {
        db = QSqlDatabase::addDatabase("QSQLITE");
        QString name = getDatabaseName();
        db.setDatabaseName(name);
        if (!db.open())
        {
            qDebug() << QString("open %s false!").arg(name) << endl;
            return false;
        }
    }

    QSqlQuery query;
    query.exec(QString("create table if not exists affairs ("
                       "guid varchar not null primary key,"
                       "addTime TIMESTAMP default(datetime('now', 'localtime')),"
                       "effect varchar,"
                       "done int default(0),"
                       "doneTime TIMESTAMP default(datetime('now', 'localtime')))"));

    return true;
}
